package jun.empdepmanagersystem02.until;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import jun.empdepmanagersystem02.pojo.Result;


import java.util.Calendar;
import java.util.Map;

public class JWTuntils {
    //    1.指定签名秘钥
    private static final String signature = "Jun!!login_kkkey";

    public static String getToken(Map<String, String> payload) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 15);
        try {
//            选择签名方法 并将秘钥传进方法中生成签名体
            Algorithm algorithm = Algorithm.HMAC256(signature);

//            JWT参数构建体创建
            JWTCreator.Builder tokenBuilder = JWT.create();

            payload.forEach(
                    (key, value) -> tokenBuilder.withClaim(key, value)
            );
            tokenBuilder.withExpiresAt(calendar.getTime());
//token
            String token = tokenBuilder
                    .sign(algorithm);
            return token;
        } catch (JWTCreationException exception) {
            // Invalid Signing configuration / Couldn't convert Claims.
        }


        return null;
    }

    public static Result verify(String token) {
        DecodedJWT decodedJWT;
        try {
            Algorithm algorithm = Algorithm.HMAC256(signature);
            JWTVerifier verifier = JWT.require(algorithm)
                    // specify an specific claim validations
                    // reusable verifier instance
                    .build();
            decodedJWT = verifier.verify(token);
            return Result.success("Token验证成功", decodedJWT.getClaims().get("username").asString());

        } catch (JWTVerificationException exception) {
            // Invalid signature/claims
            return Result.error("NOT_LOGIN");
        }
    }

}
